package com.ruoyi.files.controller;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.files.domain.SysFileInfo;
import com.ruoyi.files.service.ISysFileInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 文件信息Controller
 * -ui
 * @author ruoyi
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/files/files")
public class SysFileInfoController extends BaseController
{
    @Autowired
    private ISysFileInfoService sysFileInfoService;
    public static String extractByRegex(String text, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "未找到";
    }
    private static final String PYTHON_SCRIPT_PATH = "ruoyi-admin/src/main/resources/python/demo.py";

    @PostMapping("/fillData")
    @ResponseBody
    //@PreAuthorize("@ss.hasPermi('files:files:list')")
    public Map<String, Object> getKeyValue(@RequestBody Map<Object,String> text) {
        String txt = text.get("txt");
        System.out.println(txt);

//        Map<String, Object> result = new HashMap<>();
//        result.put("ethnicity", "汉族");
//        result.put("politicalStatus", "共青团员");
//        result.put("college", "内蒙古农业大学");
//        result.put("major", "现代文秘");
//        result.put("registrationNumber", "011412");
//        result.put("candidateNumber", "2417");
//        result.put("address", "内蒙古自治区呼和浩特市玉泉区闪亮99。凯德广场店");
//        result.put("recipient", "彭飞");
//        result.put("postalCode", "750312");
//        result.put("language", "英语");
//        //我的姓名是彭程，民族是汉族，政治面貌是共青团员，专科院校是内蒙古农业大学专科，专科专业是现代文秘，报名号是011412，考生号是2417，通知书邮寄地址是内蒙古自治区呼和浩特市玉泉区闪亮99。凯德广场店，
//        // 通知书收件人是彭南科，邮编是750312，外语种是英语，考点模式是阿拉善盟，考点专业是新闻学，志愿院校是呼伦贝尔学院，志愿专业是汉语言文学
//        return result;

        Map<String, Object> entities = new HashMap<>();
        entities.put("text", txt);
//        entities.put("姓名", extractByRegex(text, "姓名是([^，]+)"));
//        entities.put("民族", extractByRegex(text, "民族是([^，]+)"));
//        entities.put("政治面貌", extractByRegex(text, "政治面貌是([^，]+)"));
//        entities.put("专科院校", extractByRegex(text, "专科院校是([^，]+)"));
//        entities.put("专科专业", extractByRegex(text, "专科专业是([^，]+)"));
//        entities.put("报名号", extractByRegex(text, "报名号是([^，]+)"));
//        entities.put("考生号", extractByRegex(text, "考生号是([^，]+)"));
//        entities.put("通知书邮寄地址", extractByRegex(text, "通知书邮寄地址是(.*?)，"));
//        entities.put("通知书收件人", extractByRegex(text, "通知书收件人是([^，]+)"));
//        entities.put("邮编", extractByRegex(text, "邮编是([^，]+)"));
//        entities.put("外语种", extractByRegex(text, "外语种是([^，]+)"));
//        entities.put("考点模式", extractByRegex(text, "考点模式是([^，]+)"));
//        entities.put("考点专业", extractByRegex(text, "考点专业是([^，]+)"));
//        entities.put("志愿院校", extractByRegex(text, "志愿院校是([^，]+)"));
//        entities.put("志愿专业", extractByRegex(text, "志愿专业是([^，]+)"));

        // 将Map转换为JSON字符串
       ObjectMapper mapper = new ObjectMapper();
        String jsonInput;
        try {
            jsonInput = mapper.writeValueAsString(entities);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH, jsonInput);

        System.out.println("jsonOutput = " + jsonOutput);
        // 调用Python脚本并传递JSON字符串
        //String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH, jsonInput);

        // 将返回的JSON字符串转换回Map
        Map<String, Object> result;
        try {
            result = mapper.readValue(jsonOutput, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        System.out.println("result = " + result.toString());
        return result;

    }

    private String callPythonScript(String scriptPath, String jsonInput) {
        // 构建命令
        List<String> commands = Arrays.asList("D:\\Anaconda\\envs\\ljqenv\\python.exe", scriptPath);

        // 使用ProcessBuilder执行Python脚本
        ProcessBuilder processBuilder = new ProcessBuilder("D:\\Anaconda\\envs\\ljqenv\\python.exe",scriptPath,jsonInput);
        processBuilder.redirectErrorStream(true);
        //processBuilder.environment().forEach((key, value) -> System.out.println(key + " => " + value));

        processBuilder.environment().put("PYTHONIOENCODING", "UTF-8");
        try {
            Process process = processBuilder.start();

            // 向Python脚本的标准输入写入JSON字符串
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
//            writer.write(jsonInput);
//            writer.newLine();
//            writer.flush();
//            writer.close();

            // 读取Python脚本的标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            process.waitFor();

            // 仅返回最后的JSON输出
            String[] lines = output.toString().split("\n");
            for (String str : lines) {
                if (str.startsWith("{") && str.endsWith("}")) {
                    str = str.replace("'","\"");
                    return str;
                }
            }
            return null;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 查询文件信息列表
     */
    @PreAuthorize("@ss.hasPermi('files:files:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysFileInfo sysFileInfo)
    {
        startPage();
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('files:files:add')")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, SysFileInfo fileInfo) throws IOException
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        if("jpg".equals(FileUploadUtils.getExtension(file))||"png".equals(FileUploadUtils.getExtension(file))||"jpeg".equals(FileUploadUtils.getExtension(file))){
            filePath=filePath+"/pic";
        }else{
            filePath=filePath+"/doc";
        }
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        fileInfo.setFilePath(fileName);
        return toAjax(sysFileInfoService.insertSysFileInfo(fileInfo));
    }
    /**
     * 通用下载请求
     *
     * @param fileId 文件名称
     * @param delete 是否删除
     */
    @PreAuthorize("@ss.hasPermi('files:files:add')")
    @GetMapping("/downloadById")
    public void fileDownloadById(Long fileId, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {

            String fileName = sysFileInfoService.selectSysFileInfoByFileId(fileId).getFileName();
            String filePath = sysFileInfoService.selectSysFileInfoByFileId(fileId).getFilePath();
            System.out.println(fileName);
            System.out.println(filePath);
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            filePath=filePath.replace("/profile","E:/JAVA/Code/ruoyi/bakFile");
            System.out.println(filePath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 导出文件信息列表
     */
    @PreAuthorize("@ss.hasPermi('files:files:export')")
    @Log(title = "文件信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFileInfo sysFileInfo)
    {
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        ExcelUtil<SysFileInfo> util = new ExcelUtil<SysFileInfo>(SysFileInfo.class);
        util.exportExcel(response, list, "文件信息数据");
    }

    /**
     * 获取文件信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(sysFileInfoService.selectSysFileInfoByFileId(fileId));
    }

    /**
     * 新增文件信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:add')")
    @Log(title = "文件信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysFileInfo sysFileInfo)
    {
        return toAjax(sysFileInfoService.insertSysFileInfo(sysFileInfo));
    }

    /**
     * 修改文件信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:edit')")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysFileInfo sysFileInfo)
    {
        return toAjax(sysFileInfoService.updateSysFileInfo(sysFileInfo));
    }

    /**
     * 删除文件信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:remove')")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(sysFileInfoService.deleteSysFileInfoByFileIds(fileIds));
    }


//    public static void main(String[] args) {
//        File currentDir = new File(".");
//        String currentPath = currentDir.getAbsolutePath();
//        String trimmedPath = currentPath.replaceFirst("\\.$", "");
//        String script = trimmedPath + "ruoyi-admin/src/main/resources/python/demo_old.py";
//        callPythonScript(script);
//        //System.out.println("Current working directory: " + currentPath);
//    }
//public static void main(String[] args) {
//        String text="我的姓名是彭程，民族是汉族，政治面貌是共青团员，专科院校是内蒙古农业大学专科，专科专业是现代文秘，报名号是011412，考生号是2417，通知书邮寄地址是内蒙古自治区呼和浩特市玉泉区闪亮99。凯德广场店，通知书收件人是彭南科，邮编是750312，外语种是英语，考点模式是阿拉善盟，考点专业是新闻学，志愿院校是呼伦贝尔学院，志愿专业是汉语言文学";
//    Map<String, Object> entities = new HashMap<>();
//    entities.put("姓名", extractByRegex(text, "姓名是([^，]+)"));
//    entities.put("民族", extractByRegex(text, "民族是([^，]+)"));
//    entities.put("政治面貌", extractByRegex(text, "政治面貌是([^，]+)"));
//    entities.put("专科院校", extractByRegex(text, "专科院校是([^，]+)"));
//    entities.put("专科专业", extractByRegex(text, "专科专业是([^，]+)"));
//    entities.put("报名号", extractByRegex(text, "报名号是([^，]+)"));
//    entities.put("考生号", extractByRegex(text, "考生号是([^，]+)"));
//    entities.put("通知书邮寄地址", extractByRegex(text, "通知书邮寄地址是(.*?)，"));
//    entities.put("通知书收件人", extractByRegex(text, "通知书收件人是([^，]+)"));
//    entities.put("邮编", extractByRegex(text, "邮编是([^，]+)"));
//    entities.put("外语种", extractByRegex(text, "外语种是([^，]+)"));
//    entities.put("考点模式", extractByRegex(text, "考点模式是([^，]+)"));
//    entities.put("考点专业", extractByRegex(text, "考点专业是([^，]+)"));
//    entities.put("志愿院校", extractByRegex(text, "志愿院校是([^，]+)"));
//    entities.put("志愿专业", extractByRegex(text, "志愿专业是([^，]+)"));
//    System.out.println(entities);
//}
}
